package eip.chapter3.pubsub.impl;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.axiom.om.OMElement;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import eip.chapter3.pubsub.RegulationUpdate;

/**
 * This class is a simple facade to the real HotelService. We use
 * the HotelService we've already implemented in the mule example
 * for the real functionality. This class just implements the  
 * publish method on which it can receive updates.
 * 
 * @author nl24167
 */
public class HotelServiceFacade {

	private final static String ID = "id";
	private final static String NAME = "name";
	private final static String DESCRIPTION = "description";
	
	private final static Logger LOG = Logger.getLogger(HotelServiceFacade.class);
	
	public void publish(OMElement param) throws Exception {
		LOG.debug("HotelServiceFacade received:" + param);
		HotelServiceImpl service = new HotelServiceImpl();
		service.setName("FromFacade");
		service.processRegulationUpdates(getRegulationList(param.toString()));
	}
	
	/**
	 * Transform the regulations from a string to a list of regulations.
	 * 
	 * @param message the xml message to transform
	 * @return the result of the xml messages
	 * @throws DocumentException if an error occurs.
	 */
	@SuppressWarnings("unchecked")
	private List<RegulationUpdate> getRegulationList(String message) throws DocumentException {
		SAXReader reader = new SAXReader();
		Document document = reader.read(new StringReader(message));
		List elements = document.getRootElement().elements();
		ArrayList regulationList = new ArrayList<RegulationUpdate>();
		for (int i = 0 ; i < elements.size() ; i++) {
			Element regulationElement = (Element) elements.get(i);
			int id = Integer.parseInt(regulationElement.attribute(ID).getText());
			String name = regulationElement.elementText(NAME);
			String description = regulationElement.elementText(DESCRIPTION);
			
			regulationList.add(new RegulationUpdate(id,name,description));
		}
		return regulationList;
	}	
	
}